package com.naicha.wechat.wechat.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * @author NaiCha
 * @date 2019/4/3
 * @description 公共方法
 */
@Slf4j
public class CommonFunction {

    /**
     * 响应数据流
     * @param response
     * @param result
     */
    public static void responseWrite(HttpServletResponse response, Object result, @Nullable Map<String,String> headers){
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.OK.value());
            response.addHeader("Access-Control-Allow-Origin", "*");
            if(headers != null && !headers.isEmpty()){
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    response.setHeader(next.getKey(),next.getValue());
                }
            }
            response.getWriter().write(GsonUtil.toJson(result));
        } catch (IOException e) {
            log.error("ResponseException",e);
        }
    }

}
